package com.app.utils;

import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.ImageView;

import com.app.application.MyApplication;
import com.app.config.AppConfig;
import com.app.config.UserConfig;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.BitmapManager;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.Reachability;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.secure.EncodeMD5;
import com.lepu.app.fun.chat.core.ClientChatXmppImpl;
import com.lepu.app.fun.chat.util.AppCommonService;
import com.lepu.app.fun.my.MyUserInfoActivity;
import com.lepu.app.fun.my.MyUserModifyNameActivity;
import com.lepu.app.fun.my.MyUserOtherInfoActivity;
import com.lepu.app.main.activity.AppQianDaoActivity;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.LoginActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.pasm.R;
import com.lidroid.xutils.BitmapUtils;

import org.jivesoftware.smack.XMPPConnection;

/*
 * 登录检查封装
 */
public class LoginUtil {

    public static final String DEFAULT_USER_ID = "-1";

    public static boolean jumpLogin(BaseFragmentActivity baseFragmentActivity) {
        boolean flag = false;
        if (!checkIsLogin()) {
            Intent intent = new Intent(baseFragmentActivity,
                    LoginActivity.class);
            baseFragmentActivity.startActivityAnim(intent,
                    R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
            flag = true;
        }
        return flag;
    }

    public static boolean checkIsLogin() {
        boolean flag = false;

        LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
        if (loginInfo != null && !TextUtils.isEmpty(loginInfo.LoginToken)) {
            flag = true;
        }

        return flag;
    }

    public static boolean checkIsBond() {
        boolean flag = false;

        LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
        if (loginInfo != null && !TextUtils.isEmpty(loginInfo.MobilePhone)) {
            flag = true;
        }

        return flag;
    }

    public static String getUserId() {
        String userId = DEFAULT_USER_ID;// default -1 不能修改这个默认值

        if (checkIsLogin()) {
            userId = MyApplication.getInstance().getLoginInfo().UserID;
        }
        return userId;
    }

    public static String getLoginToken() {
        String token = "";

        if (checkIsLogin()) {
            token = MyApplication.getInstance().getLoginInfo().LoginToken;
        }
        return token;
    }

    public static boolean isOldUser(String nickName) {
        boolean flag = false;

        if (checkIsLogin()) {
            String phone = MyApplication.getInstance().getLoginInfo().MobilePhone;
            if (!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(nickName)
                    && nickName.equals(phone)) {
                flag = true;
            }
        }

        return flag;
    }

    public static void loginOut() {
        UserConfig.setConfig(MyApplication.getInstance(),
                Const.CONFIG_APP_LOGIN_INFO, "");
        MyApplication.getInstance().setLoginInfo(null);
        // set chatsession_message
        AppCommonService.getInstance().logoutXGXMPP();

        ObserverManager.getInstance().notify(
                ObserverConst.NOTIFY_MY_LOGIN_STATE_CHANGE, null,
                LoginInfo.TYPE_LOGOUT);
    }

    public static void jumpUserInfo(BaseFragmentActivity baseFragmentActivity,
                                    String userId) {
        if (!checkIsLogin()) {
            LoginUtil.jumpLogin(baseFragmentActivity);
        } else {
            if (userId.equals(getUserId())) {
                Intent intent = new Intent(baseFragmentActivity,
                        MyUserInfoActivity.class);
                baseFragmentActivity.startActivity(intent, true);
            } else {
                Intent intent = new Intent(baseFragmentActivity,
                        MyUserOtherInfoActivity.class);
                intent.putExtra("targetId", userId);
                baseFragmentActivity.startActivity(intent, true);
            }
        }
    }

    public static void jumpIntegral(BaseFragmentActivity baseFragmentActivity,
                                    int integral) {
        if (integral == 0) {
            return;
        }
        Intent intentAnima = new Intent(baseFragmentActivity,
                AppQianDaoActivity.class);
        intentAnima.putExtra("integral", String.valueOf(integral));
        baseFragmentActivity.startActivity(intentAnima);
    }

    /**
     * 程序启动时使用无动画跳转主程序
     *
     * @param context
     */
    public static void jumpMainActivity(BaseFragmentActivity context) {
        if (MainTabActivity.getInstance() == null) {
            Intent intent = new Intent(context, MainTabActivity.class);
            context.startActivityAnim(intent, 0, 0);
        }
    }

    /**
     * 完善资料时，跳转使用，程序强制用户完善资料
     *
     * @param context
     */
    public static void jumpUserInfoActivity(BaseFragmentActivity context) {
        Intent intent = new Intent(context, MyUserInfoActivity.class);
        intent.putExtra("first_enter", true);
        context.startActivity(intent, true);
    }

    /**
     * 检查是否完善了信息
     *
     * @return
     */
    public static boolean checkNeedFinishInfo(LoginInfo loginInfo) {
        boolean flag = false;

        if (loginInfo == null
                || (TextUtils.isEmpty(loginInfo.TrueName) && TextUtils
                .isEmpty(loginInfo.BirthYear))) {
            flag = true;
        }
        return flag;
    }

    public static void savePassword(Context context, String pwd) {
        pwd = EncodeMD5.getMd5(pwd);
        AppConfig.setConfig(context, Const.CONFIG_APP_USER_PWD, pwd);
    }

    public static String getPassword(Context context) {
        String pwd = AppConfig.getConfigString(context,
                Const.CONFIG_APP_USER_PWD, "");

        return pwd;
    }

    public static void getUserIcon(Context context, ImageView imageView,
                                   String UserID, boolean fromNet) {

        imageView.setImageResource(R.drawable.app_ic_default_avatar);

        String filePath = SdLocal.getUserPath(context, UserID);
        String imageUrl = Setting.getHeadIconUrl(UserID);

        if (!TextUtils.isEmpty(imageUrl)) {
            BitmapManager.getInstance().loadBitmap(imageUrl, filePath,
                    imageView, null, fromNet);
        }
    }

    public static void updateStaffMsgNewCount() {
        String key = LoginUtil.getUserId() + "_"
                + Const.CONFIG_APP_ONLINE_STAFF_MSG_NEW_COUNT;
        int count = getStaffMsgNewCount();
        count = (count + 1);

        AppConfig.setConfig(MyApplication.getInstance(), key, count);
    }

    public static int getStaffMsgNewCount() {

        String key = LoginUtil.getUserId() + "_"
                + Const.CONFIG_APP_ONLINE_STAFF_MSG_NEW_COUNT;

        int count = 0;
        count = AppConfig.getConfigInt(MyApplication.getInstance(), key, 0);
        return count;
    }

    public static void clearStaffMsgNewCount() {

        String key = LoginUtil.getUserId() + "_"
                + Const.CONFIG_APP_ONLINE_STAFF_MSG_NEW_COUNT;

        AppConfig.setConfig(MyApplication.getInstance(), key, 0);
    }

    public static void clearUserIcon(Context context) {
        String filePath = SdLocal.getUserPath(context, LoginUtil.getUserId());
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        BitmapManager.clearBitmapMemoryCache();
    }

    /**
     * 当用户修改图片时调用
     * @param context
     */
    public static void clearUserCacheImage(Context context)
    {
        String imageUrl = Setting.getHeadIconUrl(LoginUtil.getUserId());
        HeadIconLoadUtil.bitmapUtils.clearMemoryCache(imageUrl);
        HeadIconLoadUtil.bitmapUtils.clearDiskCache(imageUrl);
        HeadIconLoadUtil.bitmapUtils.clearCache(imageUrl);
    }

    /**
     * 加载用户头像
     * @param context
     * @param iconImageView
     * @param otherUserId
     */
    public static void loadSelfUserImage(Context context,
                                         ImageView iconImageView, String otherUserId) {

        String imageUrl = Setting.getHeadIconUrl(otherUserId);
        String selfUserId = LoginUtil.getUserId();
        if (selfUserId.equals(otherUserId)) {
            //clearUserCacheImage(context);
            //当本地修改图片时，clear
        }
        HeadIconLoadUtil.displayImage(R.drawable.app_ic_default_avatar, imageUrl, iconImageView);
    }

    public static void loadSelfUserImage(Context context,
                                         ImageView iconImageView, String otherUserId,int resDefaultId) {

        String imageUrl = Setting.getHeadIconUrl(otherUserId);
        String selfUserId = LoginUtil.getUserId();
        if (selfUserId.equals(otherUserId)) {
            //clearUserCacheImage(context);
            //当本地修改图片时，clear
        }
        HeadIconLoadUtil.displayImage(resDefaultId, imageUrl, iconImageView);
    }

    public static boolean checkNamePhone(BaseFragmentActivity baseFragmentActivity,String name, String phone){
        boolean flag = false;
        if(name == null || name.equals("") || name.length() < 11 ||
                phone == null || phone.equals("") || phone.length() < 11){
            flag = false;
        }else{
            String nameString = name.substring(0, 3)+name.substring(7, 11);
            String phoneString = phone.substring(0, 3)+phone.substring(7, 11);
            if(nameString.equals(phoneString) && name.contains("*")){
                flag = true;
            }
        }

        return flag;
    }

    public static void loginOpenFire()
    {
        if (Reachability.checkNetwork(MyApplication.getInstance())
                && ClientChatXmppImpl.getInstance().isConnectionClosed()) {
            try {
                XMPPConnection connection = ClientChatXmppImpl.getInstance()
                        .getConnection();
                if (connection != null && connection.isConnected()) {
                    AppCommonService.getInstance().logoutXGXMPP();
                    // return;
                    Thread.sleep(1000);
                }

                if (LoginUtil.checkIsLogin()
                        && (connection == null || !connection.isConnected())) {
                    LogUtilBase.LogD(null, "AppCommonService setupChatService");
                    AppCommonService.getInstance().setupChatService();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //============
    public static void updateChatNoticeNewCount(int countAdd) {
        String key = LoginUtil.getUserId() + "_"
                + Const.CONFIG_APP_CHAT_NOTICE_NEW_COUNT;
        int count = getChatNoticeCount();
        count = (count + countAdd);

        AppConfig.setConfig(MyApplication.getInstance(), key, count);
    }

    public static int getChatNoticeCount() {

        String key = LoginUtil.getUserId() + "_"
                + Const.CONFIG_APP_CHAT_NOTICE_NEW_COUNT;

        int count = 0;
        count = AppConfig.getConfigInt(MyApplication.getInstance(), key, 0);
        return count;
    }

    public static void clearChatNoticeCount() {

        String key = LoginUtil.getUserId() + "_"
                + Const.CONFIG_APP_CHAT_NOTICE_NEW_COUNT;

        AppConfig.setConfig(MyApplication.getInstance(), key, 0);
    }

}
